package com.guige.convert.controller;

import com.alibaba.fastjson.JSON;
import com.guige.base.exception.BusinessException;
import com.guige.base.exception.vo.MessageVo;
import com.guige.base.util.StringUtils;
import com.guige.convert.model.dto.ParserFileDto;
import com.guige.convert.model.vo.ParserFileVo;
import com.guige.convert.producer.ConvertProducer;
import com.guige.convert.service.ConvertService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;


/**
 * 解析controller
 *
 * @author songaw
 * @date 2017/7/24 17:08
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/convert")
public class ConvertController {
    @Autowired
    ConvertService convertService;

    @RequestMapping(value = "/xls", method = RequestMethod.POST)
    public MessageVo<ParserFileDto> uploadFile(@RequestBody @Valid ParserFileVo parserFileVo) {


        MessageVo<ParserFileDto> messageVo = convertService.convert(parserFileVo,"htmlToExcel");
        return messageVo;

    }

    /**
     * 前端界面接口
     *
     * @param uploadfile
     * @return
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public MessageVo uploadFile(MultipartFile uploadfile, @RequestParam(name = "type", defaultValue = "htmlToExcel", required = false) String type, HttpServletResponse response) {
        try {

            if (uploadfile == null) {
                throw new BusinessException("文件不能为空");
            }
            String data = new String(Base64.encodeBase64(uploadfile.getBytes()), "utf-8");
            ParserFileVo parserFileVo = new ParserFileVo();
            parserFileVo.setBaseFile(data);
            parserFileVo.setFileName(uploadfile.getOriginalFilename());

            MessageVo<ParserFileDto> messageVo = convertService.convert(parserFileVo,type);

            return messageVo;


        } catch (IOException e) {
            throw new BusinessException("error.0003", e);
        }
    }

}
